package com.aimei520.service.impl;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.aimei520.mapper.AdminMapper;
import com.aimei520.mapper.LoginMapper;
import com.aimei520.po.admin.Url;
import com.aimei520.po.admin.User;
import com.aimei520.po.meun.Menu;
import com.aimei520.service.api.LoginService;
import com.aimei520.utils.Encryption;
import com.aimei520.utils.MenuTree;

@Service
public class LoginServiceImpl implements LoginService {

	@Resource
	private LoginMapper loginMapper;
	
	@Resource
	private AdminMapper adminMapper;
	
	@Override
	public List<Menu> findMenu( User user) {
		
		List<Menu> menu = loginMapper.findMenu(user.getRole().getId());
		for (Menu menu_item : menu) {
			List<Menu> childMenu = loginMapper.findMenu_child(user.getRole().getId(), menu_item.getId());
			menu_item.setChildMenu(childMenu);
		}
		return menu;
	}

	@Override
	public List<Menu> findMenu_byRole(User user) {
		List<Menu> menulist = new ArrayList<Menu>();
		menulist = loginMapper.findAllMenu_byRoleId(user.getRole().getId());
		MenuTree menuTree = new MenuTree();
		return menuTree.menuList2(menulist);
	}

	@Override
	public boolean doLogin(User user,HttpSession session) throws NoSuchAlgorithmException {
		
		User userQueryVo = new User();
		userQueryVo.setUsername(user.getUsername());
		List<User> userByQuery = loginMapper.queryUser(userQueryVo);
		
		if(userByQuery.size() == 0)
			return false;
		if(!userByQuery.get(0).getPassword().equals( new Encryption( user.getPassword() ).getEncryptionPassword() ) )
			return false;
		
		session.setAttribute("user", userByQuery.get(0));
		session.setAttribute("menu", findMenu_byRole(userByQuery.get(0)));
		session.setAttribute("url", loginMapper.findAllUrl_byRoleId(userByQuery.get(0).getRoleId()));
		
		return true;
	}

}
